package com.kirk.crawler.handler;

import com.kirk.crawler.constant.SystemConstants;
import com.kirk.crawler.constant.UserConstants;
import com.kirk.crawler.core.context.CrawlerToolContextData;
import com.kirk.crawler.core.runcycle.CrawlerToolRunCycleManager;
import com.kirk.crawler.core.runcycle.ICrawlerToolRunCycle;
import com.kirk.crawler.ui.CrawlerToolLogin;
import com.kirk.crawler.ui.JSplash;
import com.kirk.crawler.ui.style.ColorDefinitions;
import com.kirk.crawler.ui.style.LookAndFeelSelector;
import com.kirk.crawler.utils.HttpProxySetUtil;
import com.kirk.crawler.webService.manager.ManagerService;
import com.kirk.crawler.webService.manager.beans.UserBean;

import javax.swing.*;
import java.net.InetAddress;

/**
 *  <p> CrawlerToolLoginHandler.java </p>
 *
 * @Author      kirkliu
 * @Date        2020-08-29 22:25
 * @version     1.0.0
 * @Description 登录页面逻辑处理类
 */
public class CrawlerToolLoginHandler extends CrawlerToolLogin {

    public CrawlerToolLoginHandler () {
        super();
    }

    /**
     * 登陆判断
     * @return 是否登陆成功
     */
    @Override
    public boolean login() {
        String errorMsg = "";
        try {
            if(Boolean.valueOf(userCacheManager.getValue(SystemConstants.NET_PROXY_SETTING_ISUSED))){
                HttpProxySetUtil.setHttpProxy(userCacheManager.getValue(SystemConstants.NET_PROXY_SETTING_HOST),
                        userCacheManager.getValue(SystemConstants.NET_PROXY_SETTING_PORT),
                        userCacheManager.getValue(SystemConstants.NET_PROXY_SETTING_DOMAIN),
                        userCacheManager.getValue(SystemConstants.NET_PROXY_SETTING_USERNAME),
                        userCacheManager.getValue(SystemConstants.NET_PROXY_SETTING_PASSWORD));
            }
            UserBean userBean = new UserBean();
            userBean.setUsername(super.userNameTextField.getText());
            userBean.setPassword(super.passwordTextField.getText());
            userBean.setLastLoginIp(InetAddress.getLocalHost().getHostAddress());
            ManagerService service = (ManagerService) CrawlerToolContextData.getInstance().getContextDataByKey(UserConstants.CONTEXT_DATA_KEY_WEBSERVICE);
            if(service != null) {
                userBean = service.login(userBean);
                if (userBean.getIsLoginSuccess()) {
                    CrawlerToolContextData.getInstance().setContextData(UserConstants.CONTEXT_DATA_KEY_USERANME, userBean);
                    if (super.rememberMe.isSelected()) {
                        // 记录柜员号到本地属性配置文件
                        saveUserIdToLocalProperty(userBean.getUsername());
                    }
                    if (!userBean.getIsAllowPerDayGather()) {
                        errorMsg = "今日采集数量已达到最大限制";
                    }
                    return true;
                } else {
                    errorMsg = userBean.getErrorMsg();
                    return false;
                }
            } else {
                throw new RuntimeException("获取连接异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            int result = JOptionPane.showConfirmDialog(null, "连接主机失败,是否离线运行?", "系统提示",JOptionPane.YES_NO_OPTION);
            if(result == 0){
                return true;
            }
            errorMsg = "连接主机失败,请检查网络配置!";
            return false;
        }finally{
            super.errorLabel.setText(errorMsg);
        }
    }

    /**
     * 登陆
     */
    @Override
    public void start() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    //设置本属性将改变窗口边框样式定义
                    //系统默认样式
                    //BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.osLookAndFeelDecorated;
                    //强立体半透明
                    //BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike;
                    //弱立体感半透明
                    //BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencySmallShadow;
                    //普通不透明
                    //BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.generalNoTranslucencyShadow;
//					UIManager.put("ToolBar.isPaintPlainBackground", Boolean.TRUE);
//					UIManager.put("RootPane.setupButtonVisible", false);
//					BeautyEyeLNFHelper.translucencyAtFrameInactive = false;
//					BeautyEyeLNFHelper.launchBeautyEyeLNF();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                LookAndFeelSelector.setLookAndFeel("OfficeBlue2007");
                ColorDefinitions.initColors();
                // 开始运行周期
                ICrawlerToolRunCycle cowSwingRunCycle = new CrawlerToolRunCycleManager();
                cowSwingRunCycle.start();
                dispose();
                JSplash.getInstance().splashOff();
            }
        });
    }


    /**
     * 保存柜员号到本地属性配置文件
     * <p>
     * 方法说明:
     * </p>
     * <li>保存柜员号到已经登录柜员号以逗号分隔</li>
     * <li>保存柜员号到最后一次</li>
     * @param userId 用户柜员号
     */
    private void saveUserIdToLocalProperty(String userId) {
        if (!userIdList.contains(userId)) {
            String tempUserId = userId;
            if (!userIdList.isEmpty()) {
                tempUserId = userId + ",";
            }
            if (null != userCacheManager.getValue(UserConstants.FILE_PROPERTY_KEY_USER_IDS)) {
                tempUserId = tempUserId + userCacheManager.getValue(UserConstants.FILE_PROPERTY_KEY_USER_IDS);
            }
            userCacheManager.setValue(UserConstants.FILE_PROPERTY_KEY_USER_IDS, tempUserId);
            userIdList.add(userId);
        }
        if (!lastUserId.equals(userId)) {
            userCacheManager.setValue(UserConstants.FILE_PROPERTY_KEY_LAST_USER_ID, userId);
            lastUserId = userId;
        }
    }
}
